﻿using System;

namespace com.foxmail.wyyuan1991.Assignment.Solver
{
    public class DichotomyLineSearcher: ILineSearchSolver
    {
        /// <summary>
        /// 搜索精度
        /// </summary>
        public double Kesi{ get; set;}
        /// <summary>
        /// 一维线性搜索--二分法
        /// </summary>
        /// <param name="df">倒函数</param>
        /// <param name="a">下界</param>
        /// <param name="b">上界</param>
        /// <param name="kesi">停止参数</param>
        /// <returns></returns>
        public double Search(Func<double, double> df, double a, double b)
        {
            double left = a;
            double right = b;
            double x = 0;
            while (Math.Abs(right - left) > Kesi)
            {
                x = (right + left) / 2;
                if (df(x) < 0)
                {
                    left = x;
                }
                else if (df(x) > 0)
                {
                    right = x;
                }
                else
                {
                    break;
                }
            }
            return x;
        }
    }
}
